package org.baicaixiaozhan.learncommon.util;

import com.google.common.collect.Maps;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * Cookie 工具集
 *
 * @since 2021/6/30
 * @author baicaixiaozhan
 */
public final class CookieUtils {

    /**
     * 设置 cookie
     *
     * @param request 目标请求
     * @param response 目标响应
     * @param keyName key name
     * @param value value
     * @param maxAge 最大存活时间
     */
    public static void set(HttpServletRequest request, HttpServletResponse response,
                           String keyName, String value, Integer maxAge) {
        // 设置cookie的key和value值
        Cookie cookie = new Cookie(keyName, value);
        // 路径
        cookie.setPath(request.getContextPath());
        // 过期时间
        cookie.setMaxAge(maxAge);
        // 添加 cookie
        response.addCookie(cookie);
    }

    /**
     * 获取 cookie
     *
     * @param request 目标请求
     * @param keyName key name
     * @return {@link Cookie}
     */
    public static Cookie get(HttpServletRequest request, String keyName) {
        return readCookieMap(request).getOrDefault(keyName, null);
    }

    /**
     * 将cookie封装成map
     *
     * @param request
     * @return
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = Maps.newConcurrentMap();
        Cookie[] cookies = request.getCookies();
        if (Objects.nonNull(cookies)) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
